<template>
  <MglMap :accessToken="accessToken"
          :mapStyle="mapStyle"
          @load="onMapLoaded">

    <!-- Adding navigation control -->
    <MglNavigationControl position="top-left"/>

    <!-- Adding Image layer -->
    <MglImageLayer
      sourceId="imageSourceId"
      :source="imageSource"
      layerId="myImageLayer"
      :layer="imageLayer"
    />

    <MglImageLayer
      sourceId="borderCountrySource"
      :source="borderCountrySource"
      layerId="borderCountryLayer"
      :layer="borderCountryLayer"
    />

    <!-- Adding GeoJSON layer -->
    <MglImageLayer
      sourceId="timeserialSourceId"
      :source="timeserialSource"
      layerId="timeserialImageLayer"
      :layer="timeserialLayer"
    />

    <logo ref="logo" class="qs-logo"></logo>
    <toolbar ref="toolbar" @toolbarMethods="toolbarMethods" class="qs-toolbar"></toolbar>

    <ndvi-legend ref="ndvi-legend" v-if="dataType === 'ndvi'" class="qs-ndvi-legend"></ndvi-legend>
    <grade-legend ref="grade-legend" v-if="dataType === 'grade'" class="qs-ndvi-legend"></grade-legend>
    <lst-legend ref="lst-legend" v-if="dataType === 'lst'" class="qs-ndvi-legend"></lst-legend>
    <lai-legend ref="lai-legend" v-if="dataType === 'lai'" class="qs-ndvi-legend"></lai-legend>
    <vsm-legend ref="vsm-legend" v-if="dataType === 'vsm'" class="qs-ndvi-legend"></vsm-legend>

    <card ref="crisiscard" card-width="300px" card-right="20px" card-top="370px" card-height="230px"></card>
    <data-time-card ref="datatimecard" card-width="400px" card-left="40px" card-top="20px" card-height="50px"></data-time-card>
    <timeseries-card ref="timeseriescard" @updateImage="updateImage" card-width="300px" card-right="20px" card-top="40px" card-height="170px"></timeseries-card>
    <chart-card ref="chartcard" card-width="650px" card-left="50px" card-bottom="80px" card-height="240px"></chart-card>
    <history-card ref="historycard" @displayHistoryData="displayHistoryData" card-width="300px" card-right="20px" card-top="220px" card-height="140px"></history-card>
  </MglMap>
</template>

<script>
import Mapbox from 'mapbox-gl'
import { MglMap, MglNavigationControl, MglGeojsonLayer, MglImageLayer,
  Logo, Toolbar, Card, TimeseriesCard, ChartCard, HistoryCard, DataTimeCard,
  NdviLegend, GradeLegend, LaiLegend, LstLegend, VsmLegend } from '../../components'

import { AnimateImage, DispalyImage } from './AnimateImage'
import screenfull from 'screenfull'
// import axios from 'axios'
import Swal from 'sweetalert2'
// import png from '../../assets/test.png'

// var frameCount = 5
// var currentImage = 0
// var _map

import {
  baseUrl,
  baseUrl2,
  currentLai,
  currentVsm,
  currentLst,
  laiTimeserialList,
  lstTimeserialList,
  vsmTimeserialList,
  ndviTimeserialList,
  gradeTimeserialList,
  gradeHistoryTimeserialList,
  currentGrade
} from './dataConfig'

export default {
  name: 'GlMap',
  components: {
    MglMap,
    MglNavigationControl,
    MglGeojsonLayer,
    MglImageLayer,
    Logo,
    Toolbar,
    NdviLegend,
    Card,
    TimeseriesCard,
    ChartCard,
    HistoryCard,
    DataTimeCard,
    GradeLegend,
    LaiLegend,
    LstLegend,
    VsmLegend
  },
  data () {
    return {
      accessToken: 'pk.eyJ1IjoibWFyb3N0emd4IiwiYSI6ImNqY2xmamF1ODA4d3YyeG8zZHhvNmJtazAifQ.HZmoxlx91c9unbKOE18jpA', // your access token. Needed if you using Mapbox maps
      mapStyle: 'mapbox://styles/marostzgx/cjclflua90i1e2rmfcetrg3ht', // your map style
      // mapStyle: 'mapbox://styles/mapbox/light-v10',
      // mapStyle: 'mapbox://styles/marostzgx/ck29tr83x04x71crmnw09j84q',
      imageSource: {
        /* type: 'image',
        url: '/img/20191210.png',
        coordinates: [
          [30, 39],
          [89.999998659, 39],
          [89.999998659, -11],
          [30, -11]
        ] */
        'type': 'raster',
        'tiles': [
          baseUrl + 'disaster:pk_lai_20200110'
        ],
        'tileSize': 256
      },
      imageLayer: {
        // ...some GeoJSON layer configuration object
        'type': 'raster',
        'source': 'imageSourceId',
        'paint': {},
        'before': 'aeroway-line'
      },

      borderCountrySource: {
        'type': 'raster',
        'tiles': [
          baseUrl2 + 'disaster:pak_province'
        ],
        'tileSize': 256
      },
      borderCountryLayer: {
        'type': 'raster',
        'source': 'borderCountrySource',
        'paint': {},
        'before': 'myImageLayer'
      },
      timeserialSource: {
        type: 'image',
        url: '/img/LAI_20191210.png',
        coordinates: [
          [60.89999931, 37.10000006],
          [79.28999931, 37.10000006],
          [79.28999931, 23.50000006],
          [60.89999931, 23.50000006]
        ]
      },
      timeserialLayer: {
        // ...some GeoJSON layer configuration object
        'type': 'raster',
        'source': 'timeserialSourceId',
        'paint': {},
        'layout': {
          'visibility': 'none'
        },
        'before': 'aeroway-line'
      },
      dataType: 'lai'
    }
  },

  created () {
    // We need to set mapbox-gl library here in order to use it in template
    this.mapbox = Mapbox
    this.map = null
  },
  methods: {
    onMapLoaded (event) {
      // in component
      this.map = event.map
      this.map.setCenter([70, 30])
      this.map.setZoom(4.5)
    },
    getPath () {
      return (
        '../../assets/test.png'
      )
    },
    displayHistoryData (data) {
      var _map = this.map
      var historyImage

      if (data.type === 'lai') {
        this.dataType = 'lai'
        historyImage = 'disaster:pk_lai_' + data.date
      } else if (data.type === 'grade') {
        this.dataType = 'grade'
        historyImage = 'disaster:pk_grade_' + data.date
      }
      DispalyImage(_map, baseUrl + historyImage, this.$refs.datatimecard)
    },
    updateImage (data) {
      // console.log(this.map.getSource('image123').updateImage({url: 'https://docs.mapbox.com/mapbox-gl-js/assets/radar1.gif'}))
      var _map = this.map
      var dataTimeDiv = this.$refs.datatimecard
      var _list
      if (data === 'lai') {
        this.dataType = 'lai'
        _list = laiTimeserialList
      } else if (data === 'lst') {
        this.dataType = 'lst'
        _list = lstTimeserialList
      } else if (data === 'vsm') {
        this.dataType = 'vsm'
        _list = vsmTimeserialList
      } else if (data === 'ndvi') {
        this.dataType = 'ndvi'
        _list = ndviTimeserialList
      } else if (data === 'grade') {
        this.dataType = 'grade'
        _list = gradeTimeserialList
      } else if (data === 'grade_history') {
        this.dataType = 'grade'
        _list = gradeHistoryTimeserialList
      } else {
        _list = laiTimeserialList
      }

      if (_list.length < 1) {
        Swal.fire({
          title: 'Error!',
          text: 'There\'s no data',
          icon: 'error',
          confirmButtonText: 'OK'
        })
      } else {
        AnimateImage(_map, _list, dataTimeDiv)
      }
    },
    toolbarMethods (data) {
      var _map = this.map
      if (data === 'zoomin') {
        this.$refs.mapboxmap.zoomIn()
      } else if (data === 'zoomout') {
        this.$refs.mapboxmap.zoomOut()
      } else if (data === 'fullscreen') {
        if (!screenfull.isEnabled) {
          this.$message({
            message: 'you browser can not work',
            type: 'warning'
          })
          return false
        }
        screenfull.toggle()
      } else if (data === 'crisis') {
        this.$refs.crisiscard.displayBtn()
      } else if (data === 'timeseries') {
        this.$refs.timeseriescard.displayBtn()
      } else if (data === 'statistics') {
        /* axios.get('/list?name=Pakistan').then(response => {
          // console.log(response.data.success)
          if (response.data.success) {
            Swal.fire({
              title: 'Error!',
              text: JSON.parse(response.data.data).length,
              icon: 'error',
              confirmButtonText: 'Cool'
            })
          }
        }, response => {
          console.log('error')
        }) */
        this.$refs.chartcard.displayBtn()
      } else if (data === 'history') {
        this.$refs.historycard.displayBtn()
      } else if (data === 'ndvi') {
        // DispalyImage(_map, '/img/20200210.png')
        Swal.fire({
          title: 'Error!',
          text: 'No NDVI data, coming soon...',
          icon: 'error',
          confirmButtonText: 'OK'
        })
      } else if (data === 'lai') {
        this.dataType = 'lai'
        this.$refs.datatimecard.dt = currentLai.split('_').slice(-1)[0]
        DispalyImage(_map, baseUrl + currentLai, this.$refs.datatimecard)
      } else if (data === 'moisture') {
        this.dataType = 'vsm'
        this.$refs.datatimecard.dt = currentVsm.split('_').slice(-1)[0]
        DispalyImage(_map, baseUrl + currentVsm, this.$refs.datatimecard)
      } else if (data === 'lst') {
        this.dataType = 'lst'
        this.$refs.datatimecard.dt = currentLst.split('_').slice(-1)[0]
        DispalyImage(_map, baseUrl + currentLst, this.$refs.datatimecard)
      } else if (data === 'grade') {
        this.dataType = 'grade'
        this.$refs.datatimecard.dt = currentGrade.split('_').slice(-1)[0]
        DispalyImage(_map, baseUrl + currentGrade, this.$refs.datatimecard)
      }
    }
  }
}
</script>

<style scoped>
  .qs-logo {
    z-index: 9999;
    position: absolute;
    bottom: 40px;
    left: 20px;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, .8);
    color: #fff;
    font-size: 28px;
    width: 77px;
    height: 21px;
  }

  .qs-toolbar {
    z-index: 9999;
    position: absolute;
    top: 120px;
    left: 12px;
    height: 350px;
    width: 30px;
  }

  .qs-ndvi-legend{
    z-index: 9999;
    position: absolute;
    bottom: 20px;
    right: 20px;
    width: 300px;
    height: 20px;
    cursor: pointer;
    -webkit-transition: .3s opacity;
    transition: .3s opacity;
    margin-bottom: 5px;
    border-radius: 20px;
  }
</style>
